package com.lagou.niancheng.mvc.dispatcher.core;

import com.alibaba.fastjson.JSONObject;
import com.lagou.niancheng.mvc.dispatcher.entity.RequestMappingMetaData;
import com.lagou.niancheng.mvc.dispatcher.entity.ScannedClassMetaData;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * MyMvcDispatcherServlet
 *
 * @description: default
 * @author: 阿秋@niancheng
 * @date: 2020/4/8
 */
public class MyMvcDispatcherServlet extends HttpServlet {

    private static final String INIT_PARAM_NAME = "scanPackage";

    private MyMvcBeanRegistry myMvcBeanRegistry;

    private MyRequestMappingRegistry myRequestMappingRegistry;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        myMvcBeanRegistry = new MyMvcBeanRegistry();
        myRequestMappingRegistry = new MyRequestMappingRegistry();
        // 创建一个包扫描器
        MyMvcScanner myMvcScanner = new MyMvcScanner();
        // 获取需要扫描的包路径
        String packageName = config.getInitParameter(INIT_PARAM_NAME);
        // 进行包扫描
        myMvcScanner.scan(packageName);
        // 获取扫描到的所有类信息
        List<ScannedClassMetaData> allClass = myMvcScanner.getAllClass();
        if (allClass == null) {
            return;
        }
        // 注册所有的bean
        myMvcBeanRegistry.registryBean(allClass);
        // 注册所有的requestMapping
        myRequestMappingRegistry.registryRequestMapping(allClass);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        // 获取请求路径
        String requestURI = req.getRequestURI();
        // 根据请求路径获取映射关系
        RequestMappingMetaData requestMappingMetaData = myRequestMappingRegistry.getRequestMappingBean(requestURI);
        if (requestMappingMetaData == null) {
            sendResponse(resp, "not found");
            return;
        }
        // 资源校验
        if (validateSecure(requestMappingMetaData, req)) {
            // 处理请求
            try {
                Object result = handleRequest(requestMappingMetaData, req);
                sendResponse(resp, result);
            } catch (Exception e) {
                e.printStackTrace();
                sendResponse(resp, e.getMessage());
            }
        }else{
            sendResponse(resp, "没有访问权限");
        }
    }

    private Object handleRequest(RequestMappingMetaData requestMappingMetaData, HttpServletRequest req) throws InvocationTargetException, IllegalAccessException {
        // 根据beanName获取bean
        String beanName = requestMappingMetaData.getBeanName();
        Object bean = myMvcBeanRegistry.getBean(beanName);
        // 获取请求处理方法
        Method mappingMethod = requestMappingMetaData.getMappingMethod();
        // 获取参数
        Object[] params = getParams(requestMappingMetaData, req);
        // 返回处理结果
        return mappingMethod.invoke(bean, params);
    }

    /**
     * 获取参数
     *
     * @param requestMappingMetaData 请求映射信息
     * @param req                    请求
     * @return 返回参数
     */
    private Object[] getParams(RequestMappingMetaData requestMappingMetaData, HttpServletRequest req) {
        Method mappingMethod = requestMappingMetaData.getMappingMethod();
        int parameterCount = mappingMethod.getParameterCount();
        Object[] params = new Object[parameterCount];
        Map<String, Integer> paramIndexMap = requestMappingMetaData.getParamIndexMap();
        paramIndexMap.forEach((name, index) -> {
            String parameter = req.getParameter(name);
            params[index] = parameter;
        });
        return params;
    }

    private boolean validateSecure(RequestMappingMetaData requestMappingMetaData, HttpServletRequest req) {
        String username = req.getParameter("username");
        Set<String> secureList = requestMappingMetaData.getSecureList();
        return secureList.contains(username);
    }

    private void sendResponse(HttpServletResponse resp, Object result) throws IOException {
        resp.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        resp.setHeader("content-type","text/html;charset=UTF-8");
        if (result instanceof String) {
            resp.getWriter().write((String) result);
        } else {
            resp.getWriter().write(JSONObject.toJSONString(result));
        }
    }
}
